var config = require('config.js');
var Crypto = require('../utils/CryptoJS.js')
var CryptoJS = Crypto.CryptoJS
// 时间格式化输出，如3:25:19 86。每1s都会调用一次
function dateformat(time_info) {
  // console.log(time_info)  
  var that = this;
  var now_time = new Date().getTime(),
    start_time = new Date(time_info.sh_start_time.replace(/-/g, '/')),
    end_time = new Date(time_info.sh_end_time.replace(/-/g, '/'));
  var time_slot = '';
  if ((now_time - start_time > 0) && (now_time - end_time < 0)) { //正在进行中
    var time_slot = end_time - now_time;
  } else if ((now_time - start_time > 0) && (now_time - end_time > 0)) { //已经结束
    // var time_slot = end_time - now_time;
  } else if ((now_time - start_time < 0) && (now_time - end_time < 0)) { //还未开始  "2017-09-08 19:25:04"
    var time_slot = start_time - now_time;
  }

  var time = time_slot / 1000;
  // 天数
  var day = Math.floor(time / 86400);
  day = day <= 9 ? '0' + day : day;
  // 小时位
  var hour = Math.floor(time % 86400 / 3600);
  hour = hour <= 9 ? '0' + hour : hour;
  // 分钟位
  var minute = Math.floor(time % 86400 % 3600 / 60);
  minute = minute <= 9 ? '0' + minute : minute;
  // 秒数
  var second = Math.floor(time % 86400 % 3600 % 60);
  second = second <= 9 ? '0' + second : second;
  if ((now_time - start_time > 0) && (now_time - end_time < 0)) { //正在进行中
    if (time_info.sh_videos) {
      that.setData({
        changetime: {
          status: true,
          videostart: 1,
          secondstatus: true,
          changeDay: day,
          changeHour: hour,
          changeMinute: minute,
          changeSecond: second
        }
      })
    } else {
      that.setData({
        changetime: {
          status: true,
          secondstatus: true,
          changeDay: day,
          changeHour: hour,
          changeMinute: minute,
          changeSecond: second
        }
      })
    }
  } else if ((now_time - start_time > 0) && (now_time - end_time > 0)) { //已经结束
    if (time_info.sh_videos) {
      that.setData({
        changetime: {
          status: false,
          videostatus: false
        }
      })
    } else {
      that.setData({
        changetime: {
          status: false
        }
      })
    }
  } else if ((now_time - start_time < 0) && (now_time - end_time < 0)) { //还未开始  "2017-09-08 19:25:04"
    // console.log(time_info)
    if (time_info.sh_start_time) {
      var a = time_info.sh_start_time.split(' ')[0].split('-')
      var b = time_info.sh_start_time.split(' ')[1].split(':')
      if (time_info.sh_videos) {
        that.setData({
          changetime: {
            status: true,
            videostart: 0,
            changeDay: day,
            changeHour: hour,
            changeMinute: minute,
            changeSecond: second
          }
        })
      } else {
        that.setData({
          changetime: {
            status: true,
            secondstatus: false,
            secondstit: a[1] + '月' + a[2] + '日 ' + b[0] + ':' + b[1] + ':' + b[2]
          }
        })
      }
    }
  } else if (that.data.goodsinfo && (now_time - start_time == 0)) {
    that.onShow();//秒杀开始刷新页面
  }
}
// request请求封装 
var sendRequest = function(url, method, data, header) {
  var token = wx.getStorageSync('token');
  var open_id = wx.getStorageSync('open_id');

  if (method == 'POST') {
    data['device'] = open_id
    data['token'] = token
    data['version'] = config.version
    data['platform'] = 'weixin'
    data['timestamp'] = Date.parse(new Date()) / 1000
    data['sign'] = this.getSign(data)
  }
  var promise = new Promise(function(resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        cookie: 'device=' + open_id + ';platform=weixin;version=' + config.version + ';token=' + token + ';'
      },
      success: resolve,
      fail: reject
    })
  });
  return promise;
};

//获取数字签名，用于数据传输的校验
function getSign(data) {
  var str = '', keys = [];

  for (var i in data) { keys.push(i); }
  keys.sort();//参数keys按照字符编码的顺序进行排序(a 应该出现在 b 之前)

  for (var i = 0; i < keys.length; i++) {
    var cur = data[keys[i]], cur_string = JSON.stringify(cur); 

    if (cur !== '' && cur != undefined && !Array.isArray(cur)) {//undefined 和 空字符串 和 数组 和 大括号，排除
      
      str = str + keys[i] + '=' + decodeURIComponent(cur) + '&';
    }
  }
  // console.log(str + 'key=40f005e9b3bc67f2652f366d7c4d1b2b')
  return CryptoJS.MD5(str + 'key=40f005e9b3bc67f2652f366d7c4d1b2b').toString().toUpperCase();
}

//页面小程序码参数获取
function getScene(options) {
  var that = this
  if (options.scene) {
    var scene = decodeURIComponent(options.scene).split('&'); //id=22&fansid=1694
    if (scene && scene.length > 0) {
      for (var i = 0; i < scene.length; i++) {
        var str = scene[i].split('=')
        if (str[0] == 'id') {
          that.setData({
            id: str[1]
          })
        } else if (str[0] == 'pid') {
          wx.setStorageSync('partner_id', str[1]);
        } else if (str[0] == 'cid') {
          wx.setStorageSync('channel_id', str[1]);
        }
      }
    }
  } else {
    that.setData({
      id: options.id
    })
    if (options.cid) {
      wx.setStorageSync('channel_id', options.cid);
    }
    if (options.pid) {
      wx.setStorageSync('partner_id', options.pid);
    } else if (options.fansid) {
      wx.setStorageSync('partner_id', options.fansid);
    } else if (options.partner_id) {
      wx.setStorageSync('partner_id', options.partner_id);
    }
  }
}

// 保存图片
function saveImage(url) {
  var that = this;
  wx.showToast({
    title: '保存中',
    icon: 'loading',
    duration: 2000
  })
  wx.saveImageToPhotosAlbum({
    filePath: url,
    success(res) {
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 2000
      })
    },
    fail(res) {
      wx.getSetting({ //scope.writePhotosAlbum
        success: (res) => {
          if (!res.authSetting["scope.writePhotosAlbum"]) {
            wx.showModal({
              title: "是否要打开设置页面重新授权",
              content: '需要获取您的公开信息（昵称、头像、相册等），请到小程序的设置中打开相册授权',
              confirmText: "去设置",
              confirmColor: "#c40000",
              showCancel: true,
              success: function (res) {
                if (res.confirm) {
                  wx.openSetting({
                    success: (res) => { }
                  })
                }
              }
            })
          }
        }
      })
    }
  })
}

// Toast提示
var showToast = function(word, num) {
  var that = this,
    time, t = 1 * (Number(num) ? Number(num) : 1);
  clearInterval(time);
  that.setData({
    toast_word: word,
    toast_flag: true
  })

  time = setTimeout(function() {
    that.setData({
      toast_flag: false
    })
  }, t * 1000)
}

module.exports = {
  getSign: getSign,
  getScene: getScene,
  saveImage: saveImage,
  showToast: showToast,
  sendRequest: sendRequest,
  dateformat: dateformat
}